<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档生成 - DocuGen</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/static/css/vendor/easymde.min.css">
    <link rel="stylesheet" href="/static/css/common.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-file-earmark-text me-2"></i>DocuGen
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/"><i class="bi bi-house me-1"></i>首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/document-generator"><i class="bi bi-file-earmark-text me-1"></i>文档生成</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/template-generator"><i class="bi bi-file-earmark-richtext me-1"></i>模板生成</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/qa"><i class="bi bi-chat-dots me-1"></i>智能问答</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="modelDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-gear me-1"></i>模型设置
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="modelDropdown">
                            <li><a class="dropdown-item model-switch" data-model="local" href="#"><i class="bi bi-cpu me-1"></i>本地模型</a></li>
                            <li><a class="dropdown-item model-switch" data-model="third_party" href="#"><i class="bi bi-cloud me-1"></i>第三方模型</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="main-content">
    <div class="container py-4">
            <div class="page-header">
                <h1 class="page-title"><i class="bi bi-file-earmark-text"></i>文档生成</h1>
            </div>
        
        <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                    <div class="card-header bg-primary text-white">
                            <h5 class="card-title">
                                <i class="bi bi-pencil-square me-2"></i>
                                创建新文档
                        </h5>
                    </div>
                    <div class="card-body">
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <label class="form-label" for="documentTitle">文档标题</label>
                                    <input type="text" class="form-control" id="documentTitle" placeholder="输入文档标题">
                                </div>
                            </div>
                            
                            <div class="row mb-4">
                                <div class="col-md-6">
                                    <label class="form-label" for="documentType">文档类型</label>
                                    <select class="form-select" id="documentType">
                                        <option value="report">报告</option>
                                        <option value="proposal">提案</option>
                                        <option value="article">文章</option>
                                        <option value="manual">手册</option>
                                        <option value="other">其他</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label" for="documentFormat">输出格式</label>
                                    <select class="form-select" id="documentFormat">
                                        <option value="markdown">Markdown</option>
                                        <option value="docx">Word文档 (.docx)</option>
                                        <option value="html">HTML</option>
                                        <option value="text">纯文本</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <label class="form-label" for="documentPrompt">文档描述</label>
                                    <textarea class="form-control" id="documentPrompt" rows="3" placeholder="请描述您需要的文档内容、结构和用途..."></textarea>
                                </div>
                            </div>
                            
                            <!-- RAG选项 -->
                            <div class="rag-options">
                                <h6 class="rag-options-title">
                                    <div class="feature-icon">
                                        <i class="bi bi-database"></i>
                                    </div>
                                    知识库增强
                                </h6>
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="useRag" checked>
                                    <label class="form-check-label" for="useRag">
                                        使用RAG增强文档质量
                                    </label>
                                </div>
                                <div class="row">
                                    <div class="col-md-8">
                                        <select class="form-select" id="ragSource" disabled>
                                            <option value="">加载知识库中...</option>
                                </select>
                            </div>
                                    <div class="col-md-4">
                                        <button class="btn btn-outline-primary w-100" id="refreshKbBtn">
                                            <i class="bi bi-arrow-clockwise"></i>刷新列表
                                </button>
                            </div>
                                </div>
                                <div class="mt-3" id="customRagSection" style="display: none;">
                                    <textarea class="form-control" id="customRagInput" rows="2" placeholder="输入自定义知识库内容，用于增强文档质量"></textarea>
                    </div>
                </div>

                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <button class="btn btn-primary w-100" id="generateBtn">
                                        <i class="bi bi-magic me-2"></i>生成大纲
                                    </button>
                    </div>
                            </div>
                            
                            <!-- 大纲生成结果 -->
                            <div id="outlineSection" style="display: none;">
                                <hr>
                                <h5 class="mb-3">生成的大纲</h5>
                                <div class="alert alert-success mb-3" role="alert">
                                    <i class="bi bi-check-circle-fill me-2"></i>
                                    大纲生成成功！您可以编辑大纲或直接生成完整文档。
                                </div>
                                
                                <div class="card mb-3">
                                    <div class="card-header bg-light">
                                        <span>大纲编辑器</span>
                                    </div>
                                    <div class="card-body p-0">
                                        <textarea id="outlineEditor" rows="15" class="form-control border-0"></textarea>
                            </div>
                        </div>
                                
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <button class="btn btn-success w-100" id="generateFullDocBtn">
                                            <i class="bi bi-file-earmark-text me-2"></i>生成完整文档
                            </button>
                        </div>
                                    <div class="col-md-6">
                                        <button class="btn btn-outline-secondary w-100" id="regenerateOutlineBtn">
                                            <i class="bi bi-arrow-repeat me-2"></i>重新生成大纲
                            </button>
                        </div>
                    </div>
                            </div>
                            
                            <div id="resultSection" style="display: none;">
                                <hr>
                                <h5 class="mb-3">完整文档</h5>
                                <div class="alert alert-success mb-3" role="alert">
                                    <i class="bi bi-check-circle-fill me-2"></i>
                                    文档生成成功！您可以编辑、复制或下载文档。
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <button class="btn btn-outline-primary w-100" id="copyBtn">
                                            <i class="bi bi-clipboard me-2"></i>复制内容
                                        </button>
                                    </div>
                                    <div class="col-md-4">
                                        <button class="btn btn-outline-success w-100" id="downloadBtn">
                                            <i class="bi bi-download me-2"></i>下载文档
                                        </button>
                                    </div>
                                    <div class="col-md-4">
                                        <button class="btn btn-outline-secondary w-100" id="regenerateBtn">
                                            <i class="bi bi-arrow-repeat me-2"></i>重新生成文档
                                        </button>
                </div>
            </div>

                                <div class="card">
                                    <div class="card-header bg-light">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span>文档编辑器</span>
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="livePreview" checked>
                                                <label class="form-check-label" for="livePreview">实时预览</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body p-0">
                                        <textarea id="editor"></textarea>
                    </div>
                            </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="text-white py-4">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="bi bi-file-earmark-text me-2"></i>DocuGen</h5>
                    <p>AI驱动的文档生成系统，让创作更高效。</p>
                </div>
                <div class="col-md-6 text-md-end">
                    <p class="mb-0">&copy; 2023 DocuGen. 保留所有权利。</p>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>
    <script>
        $(document).ready(function() {
            let currentModel = 'third_party';
            let editor = null;
            
            // 加载知识库列表
            loadKnowledgeBases();
            
            // 知识库选择逻辑
            $('#useRag').on('change', function() {
                const useRag = $(this).is(':checked');
                $('#ragSource').prop('disabled', !useRag);
                
                // 如果选择了自定义知识库，显示自定义内容输入框
                if (useRag && $('#ragSource').val() === 'custom') {
                    $('#customRagSection').show();
                } else {
                    $('#customRagSection').hide();
                }
            });
            
            // RAG相关事件处理
            $('#ragSource').on('change', function() {
                const isCustom = $(this).val() === 'custom';
                $('#customRagSection').toggle(isCustom);
            });
            
            // 刷新知识库列表
            $('#refreshKbBtn').on('click', function() {
                loadKnowledgeBases();
            });
            
            // 加载知识库列表函数
            function loadKnowledgeBases() {
                $.ajax({
                    url: '/api/kb/list',
                    type: 'GET',
                    success: function(response) {
                        if (response.success && response.data) {
                            const $select = $('#ragSource');
                            $select.empty();
                            
                            // 添加自定义选项
                            $select.append('<option value="custom">自定义知识库内容</option>');
                            
                            // 添加知识库选项
                            if (Array.isArray(response.data)) {
                                if (response.data.length > 0) {
                                    response.data.forEach(function(kb) {
                                        // 直接使用kb作为值和显示文本，因为后端已经处理好了格式
                                        $select.append(`<option value="${kb}">${kb}</option>`);
                                    });
                                    console.log("成功加载知识库列表:", response.data);
                                } else {
                                    console.log("知识库列表为空");
                                    $select.append('<option value="">没有可用的知识库</option>');
                                }
                            } else {
                                console.error("知识库数据格式错误:", response.data);
                                $select.append('<option value="">数据格式错误</option>');
                            }
                            
                            // 启用选择框
                            $select.prop('disabled', !$('#useRag').is(':checked'));
                        } else {
                            console.error("获取知识库列表失败:", response);
                            $('#ragSource').html('<option value="">加载知识库失败</option>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("请求知识库列表失败:", status, error);
                        $('#ragSource').html('<option value="">加载知识库失败</option>');
                    }
                });
            }
            
            // 生成大纲
            $('#generateBtn').on('click', function() {
                const title = $('#documentTitle').val().trim();
                const prompt = $('#documentPrompt').val().trim();
                
                if (!title) {
                    alert('请输入文档标题');
                    return;
                }
                
                if (!prompt) {
                    alert('请输入文档描述');
                    return;
                }
                
                $(this).prop('disabled', true);
                $(this).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>生成中...');
                
                // 准备请求数据
                const useRag = $('#useRag').is(':checked');
                const ragSource = useRag ? $('#ragSource').val() : '';
                const customRagContent = (useRag && ragSource === 'custom') ? $('#customRagInput').val().trim() : '';
                const docType = $('#documentType').val();
                
                $.ajax({
                    url: '/api/generate-outline',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        topic: title,
                        key_points: prompt,
                        enable_rag: useRag,
                        kb_name: ragSource,
                        custom_rag_content: customRagContent
                    }),
                    success: function(response) {
                        if (response.outline) {
                            showOutlineResult(response.outline);
                        } else {
                            alert('生成大纲失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        alert('请求失败: ' + xhr.responseText);
                    },
                    complete: function() {
                        $('#generateBtn').prop('disabled', false);
                        $('#generateBtn').html('<i class="bi bi-magic me-2"></i>生成大纲');
                    }
                });
            });

            // 显示大纲结果
            function showOutlineResult(outline) {
                $('#outlineEditor').val(outline);
                $('#outlineSection').show();
                $('html, body').animate({
                    scrollTop: $('#outlineSection').offset().top - 100
                }, 500);
            }
            
            // 生成完整文档
            $('#generateFullDocBtn').on('click', function() {
                const outline = $('#outlineEditor').val().trim();
                
                if (!outline) {
                    alert('大纲内容不能为空');
                    return;
                }
                
                $(this).prop('disabled', true);
                $(this).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>生成中...');
                
                // 先显示结果区域和编辑器
                showResult('');
                
                // 准备请求数据
                const title = $('#documentTitle').val().trim();
                const prompt = $('#documentPrompt').val().trim();
                const useRag = $('#useRag').is(':checked');
                const ragSource = useRag ? $('#ragSource').val() : '';
                const customRagContent = (useRag && ragSource === 'custom') ? $('#customRagInput').val().trim() : '';
                
                // 构建查询参数
                const params = new URLSearchParams({
                        outline: outline,
                    key_points: prompt || ''
                });
                
                if (useRag) {
                    params.append('enable_rag', 'true');
                    if (ragSource) {
                        params.append('kb_name', ragSource);
                    }
                    if (ragSource === 'custom' && customRagContent) {
                        params.append('custom_rag_content', customRagContent);
                    }
                }
                
                // 使用流式请求生成完整文档
                let eventSource;
                try {
                    console.log("开始流式生成完整文档...");
                    eventSource = new EventSource(`/api/generate-fulltext-stream?${params.toString()}`);
                    
                    let fullContent = '';
                    
                    eventSource.onopen = function() {
                        console.log("EventSource连接已打开");
                    };
                    
                    eventSource.onmessage = function(event) {
                        try {
                            console.log("收到消息:", event.data);
                            
                            // 检查是否是结束标记
                            if (event.data === '[DONE]') {
                                console.log("文档生成完成");
                                eventSource.close();
                                $('#generateFullDocBtn').prop('disabled', false);
                                $('#generateFullDocBtn').html('<i class="bi bi-file-earmark-text me-2"></i>生成完整文档');
                                return;
                            }
                            
                            const data = JSON.parse(event.data);
                            
                            if (data.thinking) {
                                // 显示思考状态
                                console.log("AI正在思考...");
                            } else if (data.content) {
                                fullContent = data.content; // 使用完整内容而不是追加
                                console.log("更新文档内容");
                                // 更新编辑器内容
                                if (editor) {
                                    editor.value(fullContent);
                                }
                            } else if (data.error) {
                                console.error("生成错误:", data.error);
                                alert(`生成失败: ${data.error}`);
                                eventSource.close();
                                $('#generateFullDocBtn').prop('disabled', false);
                                $('#generateFullDocBtn').html('<i class="bi bi-file-earmark-text me-2"></i>生成完整文档');
                            }
                        } catch (e) {
                            console.error('解析消息时出错:', e, event.data);
                            if (event.data === '[DONE]') {
                                eventSource.close();
                                $('#generateFullDocBtn').prop('disabled', false);
                                $('#generateFullDocBtn').html('<i class="bi bi-file-earmark-text me-2"></i>生成完整文档');
                                return;
                            }
                        }
                    };
                    
                    eventSource.onerror = function(error) {
                        console.error('EventSource错误:', error);
                        eventSource.close();
                        $('#generateFullDocBtn').prop('disabled', false);
                        $('#generateFullDocBtn').html('<i class="bi bi-file-earmark-text me-2"></i>生成完整文档');
                        if (!fullContent) {
                            alert('抱歉，生成文档时出现错误。请稍后再试。');
                        }
                    };
                    
                    // 添加超时处理
                    setTimeout(function() {
                        if (eventSource.readyState !== 2) { // 2 = CLOSED
                            eventSource.close();
                            $('#generateFullDocBtn').prop('disabled', false);
                            $('#generateFullDocBtn').html('<i class="bi bi-file-earmark-text me-2"></i>生成完整文档');
                            if (!fullContent) {
                                alert('生成超时，请稍后再试。');
                            }
                        }
                    }, 120000); // 2分钟超时
                    
                } catch (error) {
                    console.error('创建EventSource时出错:', error);
                    $('#generateFullDocBtn').prop('disabled', false);
                    $('#generateFullDocBtn').html('<i class="bi bi-file-earmark-text me-2"></i>生成完整文档');
                    alert('抱歉，无法建立连接。请稍后再试。');
                }
            });
            
            // 重新生成大纲
            $('#regenerateOutlineBtn').on('click', function() {
                $('#outlineSection').hide();
                $('#resultSection').hide();
                $('html, body').animate({
                    scrollTop: 0
                }, 300);
            });
            
            // 显示结果
            function showResult(content) {
                // 初始化编辑器
                if (!editor) {
                    editor = new EasyMDE({
                        element: document.getElementById('editor'),
                        autofocus: true,
                        spellChecker: false,
                        status: false,
                        minHeight: '400px',
                        maxHeight: '600px',
                        toolbar: [
                            'bold', 'italic', 'heading', '|', 
                            'quote', 'unordered-list', 'ordered-list', '|',
                            'link', 'image', 'table', '|',
                            'preview', 'side-by-side', 'fullscreen', '|',
                            'guide'
                        ]
                    });
                }
                
                // 设置编辑器内容
                editor.value(content);
                
                // 显示结果区域
                $('#resultSection').show();
                $('html, body').animate({
                    scrollTop: $('#resultSection').offset().top - 100
                }, 500);
            }
            
            // 复制内容
            $('#copyBtn').on('click', function() {
                const content = editor.value();
                navigator.clipboard.writeText(content).then(function() {
                    alert('内容已复制到剪贴板');
                }, function(err) {
                    console.error('复制失败:', err);
                    alert('复制失败，请手动选择内容并复制');
                });
            });
            
            // 下载文档
            $('#downloadBtn').on('click', function() {
                const content = editor.value();
                const title = $('#documentTitle').val().trim() || 'document';
                const format = $('#documentFormat').val();
                
                if (format === 'docx') {
                    // Word文档需要通过后端生成
                    $(this).prop('disabled', true);
                    $(this).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>生成中...');
                    
                    $.ajax({
                        url: '/api/generate-docx',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            title: title,
                            content: content
                        }),
                        success: function(response) {
                            if (response.success && response.filename) {
                                // 直接下载生成的文件
                                window.location.href = '/download/' + response.filename;
                        } else {
                                alert('生成Word文档失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                            alert('生成Word文档失败: ' + xhr.responseText);
                        },
                        complete: function() {
                            $('#downloadBtn').prop('disabled', false);
                            $('#downloadBtn').html('<i class="bi bi-download me-2"></i>下载文档');
                        }
                    });
                } else {
                    // 其他格式直接在前端生成下载
                    let extension = '';
                    let mimeType = '';
                    
                    switch (format) {
                        case 'markdown':
                            extension = 'md';
                            mimeType = 'text/markdown';
                            break;
                        case 'html':
                            extension = 'html';
                            mimeType = 'text/html';
                            break;
                        default:
                            extension = 'txt';
                            mimeType = 'text/plain';
                    }
                    
                    const blob = new Blob([content], { type: mimeType });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${title}.${extension}`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }
            });
            
            // 重新生成
            $('#regenerateBtn').on('click', function() {
                $('#resultSection').hide();
                $('html, body').animate({
                    scrollTop: $('#outlineSection').offset().top - 100
                }, 300);
            });
            
            // 实时预览切换
            $('#livePreview').on('change', function() {
                const isChecked = $(this).is(':checked');
                if (editor) {
                    if (isChecked) {
                        editor.toSideBySide();
                        } else {
                        editor.toTextArea();
                    }
                }
            });
            
            // 模型切换
            $('.model-switch').on('click', function(e) {
                e.preventDefault();
                const modelType = $(this).data('model');
                if (modelType === currentModel) return;
                
                $.ajax({
                    url: '/api/switch-model',
                    type: 'POST',
                    data: { model_type: modelType },
                    success: function(response) {
                        if (response.success) {
                            currentModel = modelType;
                            const modelName = modelType === 'local' ? '本地模型' : '第三方模型';
                            alert(`已切换到${modelName}`);
                        } else {
                            alert('模型切换失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        alert('模型切换请求失败: ' + xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html> 